<?php
namespace app\appletsapi\controller;

use app\api\extend\WxDecode;
use app\common\service\ServJwt;
use think\Db;

class Login extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @route('api/wxlogin')
     * 小程序登录
     */
    public function wxlogin()
    {
        $appId = $this->my_appid;//自己配置
        $appSecret = $this->my_appsecret;//自己配置
        $code = request()->post('code');
        $encryptedData = request()->post('encryptedData');
        $iv = request()->post('iv');
        if (empty($code) || empty($encryptedData) || empty($iv)) {
            $this->jsonresult('','-1','参数缺失');
        }
        $arr = array();
        $tempJscode2session = $this->jscode2session($code);
//        var_dump($tempJscode2session);
        if (!empty($tempJscode2session) && $tempJscode2session["is_error"] == false && !empty($tempJscode2session["data"]["openid"])) {
            $arr['openid'] = $tempJscode2session["data"]["openid"];
            $arr['session_key'] = $tempJscode2session["data"]["session_key"];
            $decodedata = new WxDecode($appId,$arr['session_key']);
            $data = $decodedata->decryptData($encryptedData,$iv,$data);
//            var_dump($data);die;
            $userdata = [
                'user_name' => $data['purePhoneNumber'],
                'openid' => $arr['openid'],
                'telphone' => $data['phoneNumber'],
                'user_type' => 3,
            ];
//            var_dump($userdata);die;
            $usermodel = new ApiUser();
            isset($tempJscode2session['data']['unionid'])?$userdata['unionid'] = $tempJscode2session['data']['unionid']:'';
            $user = Db::table('ss_user')
                ->where('telphone',$data['phoneNumber'])
                ->where('utype','in',[2,3])
                ->field('user_id,avatar,nick_name')
                ->find();
//            var_dump($user);
//            $this->result('','1','获取openid成功');
            if($user){
                $result = $usermodel->edit($userdata,$user['user_id']);
                if($result){
                    $data2 = [
                        'user' => $user,
                    ];
                    $this->jsonresult($data2,'1','成功');
                }
                $this->jsonresult('','-1','更新用户信息失败');
            } else {
                $userdata['utype'] = '3';
                $result = $usermodel->edit($userdata);
                if($result){
                    $user = $usermodel->getOne(array('user_id'=>$result),'user_id,avatar,nick_name');
                    $data2 = [
                        'user' => $user,
                    ];
                    $this->jsonresult($data2,'1','返回成功');
                }
                $this->jsonresult('','-1','获取openid失败');
            }

        } else {
            $this->jsonresult($tempJscode2session["str"],'-1','请求微信接口失败！');
        }
    }

    /**
     * @route('api/addpersonalinfo')
     * 小程序登录
     */
    public function addpersonalinfo()
    {
        $rqdata = request()->post();
        $usermodel = new ApiUser();
        $user = $usermodel->getOne(array('user_id'=>$rqdata['user_id']),'user_id,avatar,nick_name');
        if(!$user){ $this->jsonresult('','-1','不存在该用户'); }
        if(empty($rqdata['telphone']) || empty($rqdata['user_name']) || empty($rqdata['user_id'])){
            $this->jsonresult('','-1','参数缺失');
        }
        $nick_name = $this->removeEmoji($rqdata['user_name']);
        $data = [
            'telphone' => $rqdata['telphone'],
            'nick_name' => $nick_name,
            'avatar' => $rqdata['avatar'],
            'lastlogin' => time(),
            'loginip' => request()->ip(),
        ];

        $result = $usermodel->edit($data,$rqdata['user_id']);
        if($result){
            $user2 = $usermodel->getOne(array('user_id'=>$rqdata['user_id']),'user_id,avatar,telphone,nick_name,user_name,utype');
            $token = $this->generatetoken($user2);
            $data2 = [
                'user' => $user2,
                'token' => $token,
            ];
            $this->jsonresult($data2,'1','返回成功');
        }
        $this->jsonresult('','-1','更新信息失败');
    }

//    过滤微信名称头像
    public function removeEmoji($nick_name)
    {
        $nick_name = preg_replace('/[\x{1F600}-\x{1F64F}]/u', '', $nick_name);
        $nick_name = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $nick_name);
        $nick_name = preg_replace('/[\x{1F300}-\x{1F5FF}]/u', '', $nick_name);
        $nick_name = preg_replace('/[\x{1F680}-\x{1F6FF}]/u', '', $nick_name);
        $nick_name = preg_replace('/[\x{2600}-\x{26FF}]/u', '', $nick_name);
        $nick_name = preg_replace('/[\x{2700}-\x{27BF}]/u', '', $nick_name);
        $nick_name = str_replace(array('"', '\''), '', $nick_name);
        return addslashes(trim($nick_name));
    }

    private function generatetoken($user_data){
        $expireTime = 3600 * 24 * 30;
        $exp = time() + $expireTime;
        $payload_test=array(
            'iss'=>$user_data,
            'iat'=>time(),
            'exp'=>$exp,
            'nbf'=>time(),
            'sub'=>'tp.ganmiaoedu.com',
            'jti'=>md5(uniqid('JWT').time())
        );

        // 生成 token
        $jwtServer = new ServJwt();
        $token_test = $jwtServer->getToken($payload_test);
        return $token_test;
    }


}